// 1 引入 vuex  需要先安装
import { routerKey } from 'vue-router'
import { createStore } from 'vuex'


import createPersistedState from "vuex-persistedstate"


import router from '@/router/index.js'


// 创建一个新的 store 实例
const store = createStore({
  state: {
    count: 10,
    token: '',
    msg: 'vue3 项目',
    username: '',
    currentMenu: null,
    tabsList: [
      {
        path: '/',
        authName: '首页',
        label: '首页',
        icon: 'home',
        name: 'home'
      }
    ]

  },
  mutations: {
    addCount (state) {
      state.count++
    },
    // 存储token 
    setToken (state, payload) {
      state.token = payload
    },

    setUserName (state, payload) {
      state.username = payload
    },
    // 清除token
    clearToken (state, payload) {
      state.token = payload
    },

    // 存储 传递过来的导航栏菜单

    selectMenu (state, val) {
      console.log(val)

      if (val.authName == '首页') {
        state.currentMenu = null1
      } else {

        state.currentMenu = val

      }

      let res = state.tabsList.findIndex(item => item.authName == val.authName)

      res === -1 ? state.tabsList.push(val) : null

    },

    closeMenu (state, val) {
      //  1知道 当前点击的位置在哪里
      //  2 判断当前值是不是最后一项 
      let lastIndex = state.tabsList.length - 1

      let currentIndex = state.tabsList.findIndex(item => item.authName == val.authName)

      console.log(state.tabsList)


      if (currentIndex == lastIndex) {


        state.tabsList.splice(currentIndex, 1)



        router.replace({ path: '/' + state.tabsList[state.tabsList.length - 1].path })


      } else {





        state.tabsList.splice(currentIndex, 1)

        console.log('删除后的下一项', state.tabsList[currentIndex])
        router.replace({ path: '/' + state.tabsList[currentIndex].path })


      }












    }



  },
  actions: {
    asyncAddCount (context) {

      setTimeout(() => {
        context.commit('addCount')
      }, 2000)

    }
  },
  getters: {},
  modules: {},

  //  存储 state所有的数据
  plugins: [createPersistedState({
    storage: window.localStorage

  })],

  // 存储单个数据 自定义
  // plugins: [createPersistedState({
  //   storage: window.localStorage,
  //   reducer (val) {
  //     console.log(val)
  //     return {

  //       // 只储存state中的assessmentData
  //       myMsg: val.msg
  //     }
  //   }
  // })]
})

//3 导出实例
export default store